#include <iostream>
#include <pthread.h>
#include <unistd.h>
using namespace std;

void *ThreadRoutine_1(void* args){
    int i = 0;
    while(true){
        cout << "child pthread : " << getpid()  << "; name : " << (char*)args << endl;
        sleep(1);
        if(i++ == 10){
            break;
        }
    }
    cout << "new thread : " << (char*)args << " had gone\n";
    return (void*)10;       
    /*
        返回值；返回给谁？
        答：等待该线程的对象！（一般是主线程）
        
        如何获取？
        pthread_join 的第二个参数！
    */
}

void *ThreadRoutine_2(void* args){
    int i = 0;
    int *data = new int[10];            // 在堆空间申请内存！！！
    while(true){
        cout << "child pthread : " << getpid()  << "; name : " << (char*)args << endl;
        sleep(1);
        data[i]= i*10;
        if(i++ == 10) break;
    }
    cout << "new thread : " << (char*)args << " had gone\n";
    return (void*)data;
}

int main(){

    // 1. 创建线程
    pthread_t tid;
    pthread_create( &tid , nullptr, ThreadRoutine_2, (void*)"thread test");

    // 注：线程也是需要等待的！！！
    // 如果主线程不等待，则会引起类似僵尸进程的问题，导致内存泄露！

    // 2. 线程等待
#if 0
    pthread_join( tid, nullptr );
    cout << "main thread wait done ... main quit ...\n";

#else
    // 获取子线程返回值
    int* ret = nullptr;
    pthread_join( tid, (void**)&ret );
    cout << "main thread wait done ... main quit ...; new thread quit : " << endl;
    cout << "value : " ;
    for(int i = 0;i<10;i++){
        cout << ret[i] << ' ';
    }

#endif




    return 0;
}